package org.ashleygwinnell.snahs;

import java.io.File;
import java.io.IOException;

import org.ashleygwinnell.snahs.handlers.GETRequestHandler;

public class DefaultHandlers 
{

	public static GETRequestHandler getDefaultGETRequestHandler()
	{
		GETRequestHandler handler = new GETRequestHandler() {

			@Override
			public String getType() 
			{
				return "GET";
			}

			@Override
			public void handleRequest() 
			{
				for (int i = 0; i < this.getLines().size(); i++)
				{
					String line = this.getLines().get(i);
					
					if (i == 0)
					{
						String requestedFilename = line.substring(4, line.lastIndexOf("HTTP")-1);
						if (requestedFilename.equals("/"))
						{
							requestedFilename = "index.html";
						}
						this.setRequestedFilename(requestedFilename);
					}
					if (line.contains("Host:"))
					{
						this.setSourceHost(line.substring(6, line.indexOf(':', 6)));
						this.setSourcePort(line.substring(line.indexOf(':', 6) + 1));
					}
				}
				
				File file = new File(this.getServer().getFilesDirectory() + "/" + this.getRequestedFilename());
				if (file.exists())
				{
					this.setFileFound(true);
					this.setFile(file);
					String ext = file.getName().substring(file.getName().lastIndexOf(".")+1);
					
					if (ext.toLowerCase().equals("jpg"))
					{
						this.setContentType("image/jpeg");
					}
					else if (ext.toLowerCase().equals("txt"))
					{
						this.setContentType("text/plain");
					}
					else if (ext.toLowerCase().equals("html"))
					{
						this.setContentType("text/html");
					}
				}
				else
				{
					this.setFileFound(false);
					this.setFile(null);
				}
				
			}

			@Override
			public void handleResponse() throws IOException
			{
				if (this.isFileFound())
				{
					this.return200Response();
				}
				else
				{
					this.return404Response();
				}
				
			}
			
		};
		
		return handler;
	}
	
}
